using System.Collections.Generic;
using LitJson;
namespace CGF
{
    public partial class PanelMyInvites : UIComponentBase, IAwake<UILayer, bool>, IDestroy
    {
        private static Stack<string> agentIdStack = new Stack<string>();
        private string currUserId, currSearchId;
        private Table.Column[] columns;

        public static void Open()
        {
            UIManagerComponent.instance.OpenUI<PanelMyInvites>(UILayer.Normal, RootComponent.instance, false);
        }

        public static void Close()
        {
            UIManagerComponent.instance.CloseUI<PanelMyInvites>();
        }

        public async void Awake(UILayer layer, bool isFloat)
        {
            await SpawnPrefab("Prefabs/GameUI/PanelMyInvites", layer, isFloat);
            BindProperties(transform);

            BtnBack.SetClick(() =>
            {
                if (!string.IsNullOrEmpty(currSearchId))
                {
                    currSearchId = null;
                    InputSearch.text = "";
                    ReqData(currUserId);
                    return;
                }
                if (agentIdStack.Count > 0)
                {
                    ReqData(agentIdStack.Pop());
                }
                else
                {
                    Close();
                }
            });

            InputSearch.SetInputEndAction(() =>
            {
                if (!string.IsNullOrEmpty(InputSearch.text))
                {
                    BtnDelSearch.gameObject.SetActive(true);
                    Search(InputSearch.text);
                }
                else
                {
                    BtnDelSearch.gameObject.SetActive(false);
                    ReqData(currUserId);
                }
            }, false);
            
            BtnDelSearch.gameObject.SetActive(false);
            BtnDelSearch.SetClick(() =>
            {
                BtnDelSearch.gameObject.SetActive(false);
                currSearchId = null;
                InputSearch.text = "";
                ReqData(currUserId);
            });

            columns = new Table.Column[]
            {
                (cell,data) => data["id"].ToString(),
                (cell,data) => StringHelper.Format2Decimal((int)data["total_commission"] * 0.01f),
                (cell,data) => StringHelper.Format2Decimal((int)data["total_income"] * 0.01f),
                (cell,data) => data["sub_count"].ToString(),
                (cell,data) => CommAssets.instance.I18N_detail,
            };

            SetTotalCount(0);

            //表格
            ReqData(null);
        }

        private void ReqData(string userId)
        {
            currUserId = userId;
            Empty.text = CommAssets.instance.I18N_no_records;
            string api = "/v1/invite/list";
            if (!string.IsNullOrEmpty(userId))
            {
                api += "?agent_id=" + userId;
            }
            Table.GetComponent<Table>().ReqData(api, "results", columns, onAPIRes: res =>
            {
                if (res.success)
                {
                    if (string.IsNullOrEmpty(userId))
                    {
                        Title.text = I18N_my_sub;
                        InputSearch.gameObject.SetActive(true);
                    }
                    else
                    {
                        Title.text = I18N_someones_sub.Replace("{x}", userId);
                        InputSearch.gameObject.SetActive(false);
                        BtnDelSearch.gameObject.SetActive(false);
                    }
                    SetTotalCount((int)res.jsonData["data"]["allCount"]);
                }
            }, onClickCell: data =>
            {
                agentIdStack.Push(userId);
                ReqData(data["id"].ToString());
            });
        }

        private async void Search(string userId)
        {
            currSearchId = userId;
            var res = await Network.Get("/v1/invite/list?search_id=" + userId);
            if (!res.success || (int)res.jsonData["data"]["totalCount"] == 0)
            {
                Table.GetComponent<Table>().SetData(new List<JsonData>(), columns);
                Empty.gameObject.SetActive(true);
                Empty.text = I18N_no_records;
                return;
            }
            List<JsonData> list = new List<JsonData>();
            JsonData listData = res.jsonData["data"]["results"];
            for (int i = 0; i < listData.Count; i++)
            {
                list.Add(listData[i]);
            }
            Table.GetComponent<Table>().SetData(list, columns);
        }

        private void SetTotalCount(int count)
        {
            TextCount.text = $"{I18N_count}: {count}";
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
        }

    }
}
